package com.itheima.consumer;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer_Routing2 {
    public static void main(String[] args) throws IOException, TimeoutException {
//        1.创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
//        2.设置参数
        connectionFactory.setHost("192.168.0.104");//默认值为localhost
        connectionFactory.setPort(5672);//默认值为5672
        connectionFactory.setVirtualHost("/itcast");//默认值为/
        connectionFactory.setUsername("heima");
        connectionFactory.setPassword("heima");
//        3.创建连接Connection
        Connection connection = connectionFactory.newConnection();
//        4.创建Channel
        Channel channel =connection.createChannel();
//        5.创建队列Queue,如果有叫做hello_world的队列则不会创建,如果没有的话就创建
        /**
         * String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments
         * 1.queue:队列名称
         * 2.durable:是否持久化,当mq重启之后,还在
         * 3.exclusive:
         *      * 是否独占,只能有一个消费者监听这队列
         *      *当Connection关闭时,是否删除队列
         * 4.autoDelete:是否自动删除,当没有Consumer时,自动删除
         * 5.arguments:参数
         */
        channel.queueDeclare("test_direct_queue2",true,false,false,null);
//        6.接收信息

        DefaultConsumer consumer = new DefaultConsumer(channel){
            //当收到消息后会自动执行该方法

            /**
             *
             * @param consumerTag 标识
             * @param envelope 获取一些信息,交换机,路由Key
             * @param properties 配置信息
             * @param body 数据
             * @throws IOException
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//                System.out.println("consumerTag:"+consumerTag);
//                System.out.println("getExchange:"+envelope.getExchange());
//                System.out.println("RoutingKey:"+envelope.getRoutingKey());
//                System.out.println("properties:"+properties);
                System.out.println("body:"+new String(body));
                System.out.println("将信息输出到控制台");
            }
        };
        /** basicConsume(String queue, boolean autoAck, Consumer callback)
         *1. queue队列名称
         *2. autoAck:是否自动确认
         *3. callback:回调函数
         */
        channel.basicConsume("test_direct_queue2",true,consumer);
    }
}
